package org.zuel.lkq.component;


import org.apache.shiro.authc.*;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.zuel.lkq.domain.User;
import org.zuel.lkq.enums.LoginType;
import org.zuel.lkq.enums.UserStatusEnum;
import org.zuel.lkq.exception.InvalidAccountException;
import org.zuel.lkq.exception.UnpassException;
import org.zuel.lkq.exception.WaitCheckException;
import org.zuel.lkq.mapper.UserMapper;
import org.zuel.lkq.service.AuthQueryService;
import org.zuel.lkq.util.ResponseUtil;

import java.util.List;

public class UserPasswordRealm extends UserAuthRealm {

    private static final Logger log = LoggerFactory.getLogger(UserPasswordRealm.class);

    @Autowired
    private AuthQueryService authQueryService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getName() {
        return LoginType.USER_PASSWORD.getType();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof LoginToken) {
            return ((LoginToken) token).getLoginType() == LoginType.USER_PASSWORD;
        } else {
            return false;
        }
    }

    @Override
    public void setAuthorizationCacheName(String authorizationCacheName) {
        super.setAuthorizationCacheName(authorizationCacheName);
    }

    @Override
    protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = new String(upToken.getPassword());
        List<User> userList = authQueryService.queryUsername(username);
        if (userList.size() == 0) {
            throw new UnknownAccountException("用户未注册");
        }
        User user = userList.get(0);
        /*
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, user.getPassword())) {
            throw new InvalidAccountException("用户名或密码错误");
        }
        */
        Integer status = user.getStatus();
        if (UserStatusEnum.UN_CHECK.getStatus().equals(status)) {
            throw new WaitCheckException("管理员正在审核，请耐心等待一下，待会儿登录~");
        } else if (UserStatusEnum.REFUSE.getStatus().equals(status)) {
            throw new UnpassException("对不起，您申请的账号未通过审核，无法登录本系统！");
        }

        if (!password.equals(user.getPassword())) {
            throw new InvalidAccountException("用户名或密码错误");
        }
        return new SimpleAuthenticationInfo(user, password, getName());
    }

}
